﻿

function InitAutocomplete(container, source, url, onSelect, onResponse, onChange) {
    container.autoComboBox({ "url": url, paramname: "term", selected: source,
        onResponse: function (data, term, error) {
            if (typeof (onResponse) == "function") return onTransform(data, term, error);

            var result = [];
            if (error && console) console.log("problem can't construct data because returned value is broken ", arguments);
            else
                $(data).each(function (p, item) {
                    result.push({ label: item.Name, value: item.Name, valueToSet: item.Id });
                });
            if (result.length == 0)
                result.push({ label: String("<small><span class=\"notify\">(new)</span></small>   " + String(term)), value: term,valueToSet:term});

            return result;
        },
        onSelect: function (event, ui, el) {
            if (typeof (onSelect) == "function") 
                return onSelect(event, ui, el);

            if (ui.item!=null) source.val(ui.item.valueToSet);
        },
        onChange: function (event, ui, el) {            
            if (typeof (onChange) == "function")
                return onChange(event, ui, el);

            if (ui.item != null) source.val(ui.item.valueToSet);
        }
    });
}





(function ($) {
    $.widget("ui.autoComboBox", {
        options: {
            url: "",
            paramname: "id",
            onResponse: function (data, error) {
                var result = [];
                if (error && console) console.log("problem can't construct data because returned value is broken ",arguments);
                else {
                    $(data).each(function (p, item) {
                        result.push({ label: item.name, value: item.id });
                    });
                }
                return result;
            },
            onSelect: function (event, ui, el) {
                alert("default onSelect:function(event, ui,el)");
            },
            onChange: function (event, ui, el) {
                alert("default onChange:function(event, ui,el)");
            }
        },
        _create: function () {
            var self = this;
            var selected = self.options.selected ? self.options.selected : self;
            if (self.options.selected) self.options.selected.hide();
            var cvalue = selected.val() ? selected.val() : selected.text();
            var wrapper = this.wrapper = $("<span><!-- --></span>");
            wrapper.addClass("ui-combobox").appendTo(self.element);
            
            var input =this.input= $("<input type=\"text\" value=\"\" />");
            var btn = $("<a/>");
            input.appendTo(wrapper).addClass("ui-state-default ui-combobox-input ui-widget ui-widget-content ui-corner-left");
            input.val(cvalue);
            input.focus(function(){
                var curv=input.val();
                btn.trigger("click");
            });
            input.autocomplete({ delay: 500, minLength: 0, autoFocus: true,
                source: function (request, response) {
                    var qdata = { maxamount: 10 }; qdata[self.options.paramname] = request.term;
                    $.ajax({ url: self.options.url,
                        dataType: 'json',
                        data: qdata,
                        error: function (r, status, code) {
                            var result = self.options.onResponse([], qdata[self.options.paramname], status, code, r);
                            response(result);
                        },
                        success: function (data) {
                            var result = self.options.onResponse(data, qdata[self.options.paramname]);
                            response(result);
                        }
                    });
                },
                select: function (event, ui) {
                    return self.options.onSelect(event, ui, self);
                },
                change: function (event, ui) {
                    return self.options.onChange(event, ui, self);
                }
            });
            input.data("autocomplete")._renderItem = function (ul, item) {
                return $("<li></li>").data("item.autocomplete", item).append("<a>" + item.label + "</a>").appendTo(ul);
            };
            
            btn.attr("tabIndex", -1).attr("title", "Show All Items");
            btn.appendTo(wrapper);
            btn.button({ icons: { primary: "ui-icon-triangle-1-s" }, text: false });
            btn.find("span.ui-button-text").css({ display: "inline" });
            btn.css({ padding: "4px 0px" });
            btn.removeClass("ui-corner-all").addClass("ui-corner-right ui-combobox-toggle")
                    .click(function () {
                        // close if already visible
                        if (input.autocomplete("widget").is(":visible")) {
                            input.autocomplete("close");
                            //return;
                        };
                        $(this).blur();
                        input.autocomplete("search", "");                        
                    });
            input.focus();
        },

        destroy: function () {
            this.wrapper.remove();
            this.element.show();
            $.Widget.prototype.destroy.call(this);
        }
    });
})(jQuery);